<template>
	<sc-dialog v-model="visible" :title="titleMap[mode]" show-fullscreen destroy-on-close width="40%" @close="close">
		<el-form ref="formRef" label-width="100px" :model="formData" :rules="rules">
			<el-form-item label="点检单据号" prop="doc">
				<el-input v-model.trim="formData.doc" :maxlength="32" show-word-limit disabled clearable> </el-input>
			</el-form-item>
			<el-form-item label="设备" prop="equipId">
				<el-select v-model="formData.equipId" placeholder="请选择点检设备">
					<el-option
						v-for="item in templateOptions"
						:key="item.equipId"
						:label="item.equipName"
						:value="item.equipId" />
				</el-select>
			</el-form-item>
		</el-form>

		<template #footer>
			<el-button @click="close">取 消</el-button>
			<el-button :loading="isSaveing" type="primary" @click="save">确 定</el-button>
		</template>
	</sc-dialog>
</template>

<script>
export default {
    emits: ['complete'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: "新增",
				edit: "编辑",
			},
			isSaveing: false,
			visible: false,
			templateOptions: [],
			formData: {
				id: 0,
				doc: '',
				equipId: undefined,
			},
			rules: {
				doc: [{ required: true, message: "请输入点检单据号", trigger: "blur" }],
				equipId: [{ required: true, message: "请选择点检设备", trigger: "blur" }],
			},
		};
	},
	methods: {
		async open(row) {
			if (!row) {
				this.mode = "add";
				const resp =  await this.$API.common.datetimeFormat.get();
				this.formData.doc = `CK${resp.data}`;
			} else {
				this.mode = "edit";
				let resp = await this.$API.equipcheckdoc.model.get(row.id);
				this.formData = resp.data;
			}

			const resp2 = await this.$API.equipchecktemplate.list.get();
			this.templateOptions = resp2.data;
			this.visible = true;
		},
		save() {
			this.$refs.formRef.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					let resp = null;
					if (this.formData.id === 0) {
						resp = await this.$API.equipcheckdoc.add.post(this.formData);
					} else {
						resp = await this.$API.equipcheckdoc.update.put(this.formData);
					}
					this.isSaveing = false;
					if (resp.code == 200) {
						this.$emit("complete");
						this.visible = false;
						this.$message.success("保存成功");
					} else {
						this.$alert(resp.message, "提示", { type: "error" });
					}
				}
			});
		},
		close() {
			this.formData = {
				id: 0,
				doc: '',
				equipId: undefined,
			};
			this.$refs.formRef.resetFields();
			this.visible = false;
		},
	},
};
</script>
